package com.touch.sound;
import java.io.IOException;
import java.net.*;
import java.util.Vector;

import com.touch.core.util.IOTools;
public class MediaPlayer implements Runnable
{
	private MidiPlayer midiCodec;
	private MpegPlayer mpegCodec;
	private Vector<String> playList = new Vector<String>();
	private int playIndex = 0;
	private boolean loopPlayList = false;
	public void loadPlayList(final String playList) throws IOException
	{
		this.playList = this.parsePlayList(playList);	
	}
	private Vector<String> parsePlayList(final String playList) throws IOException
	{
		String songList = IOTools.readStreamAsString(new URL(playList).openStream());
		String[] songs = songList.split("\n");
		Vector<String> vPlayList = new Vector<String>();
		if(songs == null)
			return null;
		for(String song: songs)
		{
			if(!song.startsWith("#"))
			{
				if(song.toLowerCase().endsWith(".m3u"))
				{
					Vector<String> iPlayList = parsePlayList(song);
					for(String ipSong: iPlayList)
						vPlayList.add(ipSong);
				}
				vPlayList.add(song);
			}
		}
		return vPlayList;
	}
	public void loadSong(final String song) throws MalformedURLException
	{		
		if(this.midiCodec != null)
			this.midiCodec.destroy();
		if(this.mpegCodec != null)
			this.mpegCodec.destroy();
		this.midiCodec = new MidiPlayer();
		this.mpegCodec = new MpegPlayer();
		this.midiCodec.load(new URL(song));
		this.mpegCodec.load(new URL(song));		
	}
	public void play()
	{
		this.midiCodec.play();
		this.mpegCodec.play();
	}
	public void loop()
	{
		this.midiCodec.loop();
		this.mpegCodec.loop();
	}
	public void playNext() throws MalformedURLException
	{		
		if(this.playList.size() == 0)
			return;
		if(this.playIndex < this.playList.size())
		{
			this.loadSong(this.playList.elementAt(this.playIndex));
			System.out.println("playing: " + playIndex);
			this.play();
			this.playIndex ++;
		}
		else
		{
			this.playIndex = 0;
			this.playNext();			
		}	
	}
	public void play(int playListIndex) throws MalformedURLException
	{
		if(playListIndex < this.playList.size())
		{
			this.loadSong(this.playList.elementAt(playListIndex));
			this.play();
		}
	}
	public void loopPlayList()
	{
		this.loopPlayList = true;
		Thread t = new Thread(this);
		t.setName("playlist");
		t.setPriority(Thread.MIN_PRIORITY);
		t.start();
	}
	public void loop(final String code)
	{
		try
		{
			this.loadSong(code);
			this.loop();
		}
		catch (MalformedURLException e) 
		{		
			e.printStackTrace();
		}
	}
	public void stop()
	{
		midiCodec.pauseAudio();
		mpegCodec.pauseAudio();
	}
	@Override
	public void run() 
	{ 
		try 
		{
			while(loopPlayList)
			{				
				this.playNext();			
				while(midiCodec.isEnded() == false && this.mpegCodec.isEnded() == false)
					Thread.sleep(100);		
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}
}
